package com.yunyao.web.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.yunyao.common.dto.excel.ContractExcelDto;
import com.yunyao.common.dto.excel.ReconciliationExcelDto;
import com.yunyao.common.dto.excel.SettlementExcelDto;
import com.yunyao.common.dto.supplier.SupplierSettlementDto;
import com.yunyao.common.dto.supplier.SupplierSettlementMaterialDto;
import com.yunyao.common.dto.supplier.SupplierSettlementOrderDto;
import com.yunyao.common.web.util.PageResult;
import com.yunyao.common.web.util.YResult;
import com.yunyao.framework.dto.file.FileInfoDto;
import com.yunyao.framework.dto.spreconciliatioin.SpReconciliationMaterialDto;
import com.yunyao.framework.dto.supplier.SupplierSettlementApprovalDto;
import com.yunyao.framework.dto.supplier.SupplierSettlementCheckDto;
import com.yunyao.framework.dto.supplier.SupplierSettlementConfirmDto;
import com.yunyao.framework.dto.supplier.SupplierSettlementDeletedDto;
import com.yunyao.framework.dto.supplier.SupplierSettlementSaveDto;
import com.yunyao.framework.dto.supplier.SupplierSettlementSubmitApprovalDto;
import com.yunyao.framework.service.SupplierSettlementService;
import com.yunyao.framework.vo.spreconciliation.SpReconciliationMaterialVO;
import com.yunyao.framework.vo.supplier.SupplierSettlementInfoVO;
import com.yunyao.framework.vo.supplier.SupplierSettlementMaterialVO;
import com.yunyao.framework.vo.supplier.SupplierSettlementOrderVO;
import com.yunyao.framework.vo.supplier.SupplierSettlementVO;
import com.yunyao.web.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * @author xingjishuai
 * @date 2024-07-22
 */
@Slf4j
@RestController
@RequestMapping("/supplierSettlement")
public class SupplierSettlementController {
    @Autowired
    private SupplierSettlementService supplierSettlementService;

    /**
     * 供应商结算列表
     *
     * @param supplierSettlementDto
     * @return
     */
    @GetMapping("/list")
    public YResult<PageResult<SupplierSettlementVO>> pageList(SupplierSettlementDto supplierSettlementDto) {
        return supplierSettlementService.pageList(supplierSettlementDto);
    }

    /**
     * 供应商结算详情
     *
     * @param settlementDto
     * @return
     */
    @GetMapping("/info")
    public YResult<SupplierSettlementInfoVO> getInfo(SupplierSettlementDto settlementDto) {
        return supplierSettlementService.getInfo(settlementDto);
    }

    /**
     * 供应商结算材料列表
     *
     * @param supplierSettlementMaterialDto
     * @return
     */
    @GetMapping("/material/list")
    public YResult<PageResult<SupplierSettlementMaterialVO>> materialPageList(SupplierSettlementMaterialDto supplierSettlementMaterialDto) {
        return supplierSettlementService.materialPageList(supplierSettlementMaterialDto);
    }

    /**
     * @param supplierSettlementMaterialDto
     * @return
     */
    @GetMapping("/material/count")
    public YResult<Map<String, Object>> materialCount(SupplierSettlementMaterialDto supplierSettlementMaterialDto) {
        return supplierSettlementService.materialCount(supplierSettlementMaterialDto);
    }

    @GetMapping("/spreconciliationmaterial/list")
    public YResult<PageResult<SpReconciliationMaterialVO>> getContractMaterialList(SpReconciliationMaterialDto spReconciliationMaterialDto) {
        return supplierSettlementService.getSpReconciliationMaterialListbySupplyId(spReconciliationMaterialDto);
    }

    /**
     * 供应商结算对账订单列表
     *
     * @param supplierSettlementOrderDto
     * @return
     */
    @GetMapping("/order/list")
    public YResult<PageResult<SupplierSettlementOrderVO>> orderPageList(SupplierSettlementOrderDto supplierSettlementOrderDto) {
        return supplierSettlementService.orderPageList(supplierSettlementOrderDto);
    }

    @GetMapping("/getSupplyTaxTotalPrice")
    public YResult<BigDecimal> getSupplyTaxTotalPrice(String contractId) {
        return YResult.success(supplierSettlementService.getSupplyTaxTotalPrice(contractId));
    }

    /**
     * 供应商结算确认
     *
     * @param supplierSettlementConfirmDto
     * @return
     */
    @PostMapping("/confirm")
    public YResult<String> confirm(@RequestBody @Validated SupplierSettlementConfirmDto supplierSettlementConfirmDto) {
        return supplierSettlementService.confirm(supplierSettlementConfirmDto);
    }

    /**
     * 供应商云采确认
     *
     * @param supplierSettlementConfirmDto
     * @return
     */
    @PostMapping("/yc/confirm")
    public YResult<String> ycConfirm(@RequestBody @Validated SupplierSettlementConfirmDto supplierSettlementConfirmDto) {
        return supplierSettlementService.ycConfirm(supplierSettlementConfirmDto);
    }

    /**
     * 供应商结算核对
     *
     * @param supplierSettlementCheckDto
     * @return
     */
    @PostMapping("/check")
    public YResult<String> check(@RequestBody @Validated SupplierSettlementCheckDto supplierSettlementCheckDto) {
        return supplierSettlementService.check(supplierSettlementCheckDto);
    }

    /**
     * 供应商结算删除
     *
     * @param supplierSettlementDeletedDto
     * @return
     */
    @PostMapping("/deleted")
    public YResult<String> deleted(@RequestBody @Validated SupplierSettlementDeletedDto supplierSettlementDeletedDto) {
        return supplierSettlementService.deleted(supplierSettlementDeletedDto);
    }

    /**
     * 供应商结算保存
     *
     * @param supplierSettlementSaveDto
     * @return
     */
    @PostMapping("/save")
    public YResult<String> save(@RequestBody SupplierSettlementSaveDto supplierSettlementSaveDto) {
        return supplierSettlementService.save(supplierSettlementSaveDto);
    }

    @PostMapping("/submit/approval")
    public YResult<String> submitApproval(@RequestBody @Validated SupplierSettlementSubmitApprovalDto approvalDto) {
        return supplierSettlementService.submitApproval(approvalDto);
    }

    @PostMapping("/approval")
    public YResult<String> approval(@RequestBody @Validated SupplierSettlementApprovalDto approvalDto) {
        return supplierSettlementService.approval(approvalDto);
    }


    /**
     * 导出文件
     *
     * @return
     */

    @GetMapping("/export/file")
    public YResult<String> exportFile(SupplierSettlementDto supplierSettlementDto, HttpServletResponse response) {
        try {
            List<SettlementExcelDto> contractMaterialExportDtoList = supplierSettlementService.export(supplierSettlementDto);
            try {
                // 这里URLEncoder.encode可以防止中文乱码
                String fileName = URLEncoder.encode("supplierSettlement", String.valueOf(StandardCharsets.UTF_8)) + ".xlsx";
//                response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
                //设置sheet名
                ExportParams params = new ExportParams();
                params.setSheetName("结算信息模版");
                //设置标题
//                params.setTitle("商品信息");
                // 这里需要设置不关闭流
                Workbook workbook = ExcelExportUtil.exportExcel(params, SettlementExcelDto.class, contractMaterialExportDtoList);
                //输出流
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                workbook.write(bos);
                byte[] bytes = bos.toByteArray();
                bos.close();
                try {
                    FileInfoDto fileInfoDto = AliOssUtil.upload(bytes,
                            fileName, null);
                    if (null != fileInfoDto) {
                        return YResult.success(fileInfoDto.getLink());
                    } else {
                        return YResult.error("连接文件服务器失败，请重试");
                    }
                } catch (Exception e) {
                    return YResult.error("下载失败，请重试");
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        } catch (Exception e) {
            log.error("导出结算信息失败", e);
        }
        return YResult.error("导出结算信息失败");
    }
}
